import history from '@/utils/history'
import { hasToken } from '@/utils/storage'
import { Redirect, Route, RouteProps } from 'react-router'

interface Props extends RouteProps {
  path: string
  component: React.FC
}

export default function AuthRoute({
  path,
  component: Component,
  ...res
}: Props) {
  return (
    <Route
      {...res}
      path={path}
      render={() => {
        //  判断 token 是否存在
        if (hasToken()) {
          return <Component />
        } else {
          // 没有 token 重定向到登录页
          return (
            <Redirect
              to={{
                pathname: '/login',
                state: { from: history.location.pathname },
              }}
            />
          )
        }
      }}
    ></Route>
  )
}
